<template>
  <div>
  <el-dialog title="处理修改" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()">
      <!-- <el-form-item label="处理人" :label-width="formLabelWidth" prop="handUserName">
        <el-input v-model.trim="dataForm.handUserNameNew" placeholder="处理人"> </el-input>
      </el-form-item> -->
      <el-form-item label="故障类型" :label-width="formLabelWidth" prop="faultTypeIds" class="pop">
        <el-popover ref="menuListPopover" placement="bottom-start" width="auto" trigger="click"
          v-model:visible="visible">
          <template #reference>
            <el-input v-model="dataForm.faultName" @blur="visible = true" :readonly="true" placeholder="故障类型"
              class="menu-list__input"></el-input>
          </template>
          <el-tree :data="faultTypeList" :props="faultTypeListProps" node-key="id" ref="menuListTree"
            @current-change="menuListTreeCurrentChangeHandle" :default-expand-all="true" :highlight-current="true"
            :expand-on-click-node="false">
          </el-tree>
        </el-popover>
      </el-form-item>
      <el-form-item label="处理描述" :label-width="formLabelWidth" prop="handleDesc">
        <el-input v-model.trim="dataForm.handleDesc" type="textarea"> </el-input>
      </el-form-item>
      <el-form-item label="图片" :label-width="formLabelWidth" prop="icon">
        <el-upload :action="url + '/file/uploadFileInterface'" list-type="picture-card" :headers="headers"
          :file-list="fileList" :on-success="handleSuccess" :on-change="handleChange">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" v-if="!file.fileType || file.fileType == 'image'" :src=" url + file.filePath"
                alt="">
              <video v-else-if="file.fileType == 'video'" class="el-upload-list__item-thumbnail"
                style="width: 100%;height: 100%;" disabled="false" controls="false"
                :src="file.response ? file.url : url + file.filePath">
                <source :src="file.response ? file.url : url + file.filePath" type="video/mp4" />
                <source :src="file.response ? file.url : url + file.filePath" type="video/mov" />
                <source :src="file.response ? file.url : url + file.filePath" type="video/avi" />
              </video>
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in"></i>
              </span>
              <!-- <span class="el-upload-list__item-delete" @click="handleDownloadImg(file)">
                <i class="el-icon-download"></i>
              </span> -->
              <span class="el-upload-list__item-delete" @click="handleRemoveImg(file)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="dataFormSubmit()" :disabled="isDisabled">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog :visible.sync="dialogVisibleImg" :append-to-body="true" width="50%" style="height: 100%;">
            <div style="height: 60%;">
                <img style="max-width: 100%;" :src="dialogImageUrl" alt="">
            </div>

        </el-dialog>
        <el-dialog :visible.sync="dialogVisibleVideo" :append-to-body="true" width="50%" style="height: 100%;">
            <div style="height: 60%;">
                <!-- <img style="max-width: 100%;" :src="dialogImageUrl" alt=""> -->
                <video controls  style="max-width: 100%;" :autoplay="true" :src="dialogImageUrl" :show-fullscreen-btn="false"></video>
            </div>

        </el-dialog>
</div>
</template>

<script>
import { v4 as uuidv4 } from "uuid";
import { getToken } from "@/utils/auth";
import { treeDataTranslate } from '../../utils/treeDataTranslate.js'
export default {
  emits: ["refreshDataList"],
  data() {
    return {
      visible: false,
      dialogFormVisible: false,
      isDisabled: false,
      isval: false,
      isupdate: 0,
      istype: "",
      dataForm: {
        id: 0,
        handleUserId: '',//处理人
        handUserName: '',//处理人
        handUserNameNew:'',
        handleDesc: '',//处理描述
        faultTypeIds: '',
        faultTypeRootIds: '',
        faultName: ''
      },
      faultTypeList: [],
      faultTypeListProps: {
        children: 'children',
        label: 'faultName'
      },
      handleState: 0,
      productModelOptions: [],
      url: process.env.VUE_APP_BASE_API,
      headers: {
        token: getToken() //从cookie里获取token，并赋值  Authorization ，而不是token
      },
      dataRule: {
        faultTypeIds: [
          { required: true, message: '故障类型必填' },
        ],
        driverPhone: [
          { required: true, message: '司机联系电话必填' },
        ],
        licenseNumber: [
          { required: true, message: '车牌号必须填写' },
        ]
      },
      formLabelWidth: "90px",
      visible: false,
      fileList: [],
      url: process.env.VUE_APP_BASE_API,
      dialogVisibleImg: false,
      dialogVisibleVideo:false,
      dialogImageUrl: ''
    };
  },
  created() { },
  methods: {
    async init(id, handleState) {
      this.dataForm.id = id || 0;
      this.dialogFormVisible = true;
      this.handleState = handleState
      await this.Sevice({
        url: '/syn/Feedback/faultSelect',
        method: 'get',
      }).then((res) => {
        // console.log(res);
        if (res.code != 200) { } else {
          this.faultTypeList = treeDataTranslate(res.select, 'id');
        }
      })
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.dataForm.faultName = "";
        this.dataForm.faultTypeIds =''
        this.dataForm.faultTypeRootIds = ''
        this.fileList=[]
        this.productModelOptions = []
        console.log(this.$store.state.user)
        // this.dataForm.handUserName = this.$store.state.user.name;
        // this.dataForm.handleUserId = this.$store.state.user.userId;
        if (!this.handleState) {
          // 新增
          // this.treeListTreeSetCurrentNode()
        } else {
          //获取详情
          this.Sevice({
            url: "/syn/Feedback/info/" + this.dataForm.id,
            method: "get",
          }).then(async (res) => {
            // console.log(res);
            if (res.code != 200) {
              // this.$message.error(res.data.msg)
            } else {
              this.dataForm.id = res.info.id;
              this.dataForm.handleDesc = res.info.handleDesc;
              // this.dataForm.handleUserId = res.info.handleUserId;
              this.dataForm.handUserName = res.info.handUserName;
              this.dataForm.faultTypeIds = res.info.faultTypeIds?res.info.faultTypeIds:res.info.faultTypeRootIds;
              this.dataForm.faultTypeRootIds = res.info.faultTypeRootIds;
              //附件
              if (res.info.appendixUrl) {
                let appendixUrl = res.info.appendixUrl.split(',')
                let appendixName = res.info.appendixName.split(',')
                let list = []
                for (let i = 0; i < appendixUrl.length; i++) {
                  if(appendixUrl[i].indexOf('.jpg')>-1||appendixUrl[i].indexOf('.png')>-1||appendixUrl[i].indexOf('.jpeg')>-1){
                    list.push({
                      filePath: appendixUrl[i],
                        fileType:'image',
                        fileName: appendixName[i],
                  })
                  }
                  if(appendixUrl[i].indexOf('.mp4')>-1||appendixUrl[i].indexOf('.mov')>-1||appendixUrl[i].indexOf('.avi')>-1){
                    list.push({
                      filePath: appendixUrl[i],
                        fileType:'video',
                        fileName: appendixName[i],
                  })
                  }
                }
                this.fileList = list
              }
              this.menuListTreeSetCurrentNode()
            }
          });
        }
      })

    },
    handleRemoveImg(file) {
      console.log(file, this.fileList);
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid == file.uid) {
          this.fileList.splice(i, 1);
        }
      }
    },
    handlePictureCardPreview(file) {
      // this.dialogImageUrl = file.url;
      // this.dialogVisibleImg = true;
      this.dialogImageUrl = file.response?this.url+file.response.map.filePath:this.url+file.filePath;
            if(file.filePath.indexOf('.jpg') > -1|| file.filePath.indexOf('.png') > -1|| file.filePath.indexOf('.jpeg') > -1){
                this.dialogVisibleImg = true;
            }
            if(file.filePath.indexOf('.mp4') > -1|| file.filePath.indexOf('.mov') > -1|| file.filePath.indexOf('.avi') > -1){
                this.dialogVisibleVideo= true;
            }
    },
    handleDownloadImg(file) {
      this.fileDown(file);
    },
    handleSuccess(response, file, fileList) {
      if (response.code == 200) {
        let data=[]
        for(let i=0;i<fileList.length;i++){
                if(fileList[i].response){
                    if(fileList[i].response.map.filePath.indexOf('.jpg') > -1||fileList[i].response.map.filePath.indexOf('.png') > -1||fileList[i].response.map.filePath.indexOf('.jpeg') > -1){
                        data.push({filePath:fileList[i].response.map.filePath,fileType:'image',fileName:fileList[i].response.map.fileName})
                    }
                    if(fileList[i].response.map.filePath.indexOf('.mp4') > -1||fileList[i].response.map.filePath.indexOf('.mov') > -1||fileList[i].response.map.filePath.indexOf('.avi') > -1){
                        data.push({filePath:fileList[i].response.map.filePath,fileType:'video',fileName:fileList[i].response.map.fileName})
                    }
                    
                }else{
                    if(fileList[i].filePath.indexOf('.jpg') > -1||fileList[i].filePath.indexOf('.png') > -1||fileList[i].filePath.indexOf('.jpeg') > -1){
                        data.push({filePath:fileList[i].filePath,fileType:'image',fileName:fileList[i].fileName})
                    }
                    if(fileList[i].filePath.indexOf('.mp4') > -1||fileList[i].filePath.indexOf('.mov') > -1||fileList[i].filePath.indexOf('.avi') > -1){
                        data.push({filePath:fileList[i].filePath,fileType:'video',fileName:fileList[i].fileName})
                    }
                }
            }
        this.fileList = data
      } else {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid == file.uid) {
            fileList.splice(i, 1);
          }
        }
        this.$message({ message: response.msg, type: 'error', duration: 1000 })
      }
    },
    handleChange(file, fileList) {
      // this.fileList = fileList;
    },
    // 菜单树选中
    menuListTreeCurrentChangeHandle(data, node) {
      if (!data.children) {
        console.log(data)
        this.dataForm.faultTypeIds = data.id
        this.dataForm.faultName = data.faultName
        this.dataForm.faultTypeRootIds = data.parentId
        this.visible = false
      }

    },
    // 菜单树设置当前选中节点
    menuListTreeSetCurrentNode() {
      this.$refs.menuListTree.setCurrentKey(this.dataForm.faultTypeIds)
      this.dataForm.faultName = (this.$refs.menuListTree.getCurrentNode() || {})['faultName']
      this.dataForm.faultTypeRootIds = (this.$refs.menuListTree.getCurrentNode() || {})['parentId']
    },
    // 表单提交
    async dataFormSubmit() {
      this.$refs["dataForm"].validate(async (valid) => {
        if (valid) {
          let url = "/syn/Feedback/backgroundProcessing";
          this.isDisabled = true;
          //附件
          let appendixUrl = []
          let appendixName = []
          if (this.fileList.length) {
            for (let i = 0; i < this.fileList.length; i++) {
              if (this.fileList[i].response) {
                appendixUrl.push(this.fileList[i].response.map.filePath)
              } else {
                appendixUrl.push(this.fileList[i].filePath)
              }
              appendixName.push(this.fileList[i].fileName)
            }
          }
          this.dataForm.appendixUrl = appendixUrl.toString()
          this.dataForm.appendixName = appendixName.toString()
          await this.Sevice({
            url: url,
            method: "post",
            data: {
              id: this.dataForm.id || undefined,
              handleDesc: this.dataForm.handleDesc,
              // handleUserId: this.dataForm.handleUserId,
              // handleState: 1,
              // handUserName: this.dataForm.handUserNameNew,
              faultTypeIds: this.dataForm.faultTypeIds,
              faultTypeRootIds: this.dataForm.faultTypeRootIds?this.dataForm.faultTypeRootIds:this.dataForm.faultTypeIds,
              appendixUrl: this.dataForm.appendixUrl,
              appendixName: this.dataForm.appendixName,

            },
          }).then((res) => {
            if (res && res.code == 200) {
              this.dialogFormVisible = false;
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.isDisabled = false;
                  this.$emit("getMenuList");
                },
              });
            } else {
              this.isDisabled = false;
            }
          }).catch(error => {
            console.log(error)
            this.isDisabled = false;;
          });
        }
      });
    },
  },
};
</script>

<style scoped>
::v-deep .el-upload-list__item.is-ready,
	::v-deep .el-upload-list__item.is-uploading {
  		display: none !important;
	}
.mod-menu .menu-list__input>.el-input__inner,
.mod-menu .icon-list__input>.el-input__inner {
  cursor: pointer;
}

.mod-menu__icon-popover {
  width: 458px;
  overflow: hidden;
}

.mod-menu__icon-inner {
  width: 478px;
  max-height: 258px;
  overflow-x: hidden;
  overflow-y: auto;
}

.mod-menu__icon-list {
  width: 458px;
  padding: 0;
  margin: -8px 0 0 -8px;
}

.mod-menu__icon-list>.el-button {
  padding: 8px;
  margin: 8px 0 0 8px;
}

.mod-menu__icon-list>.el-button>span {
  display: inline-block;
  vertical-align: middle;
  width: 18px;
  height: 18px;
  font-size: 18px;
}

.mod-menu .icon-list__tips {
  font-size: 18px;
  text-align: center;
  color: #e6a23c;
  cursor: pointer;
}

.el-tree {
  height: 200px;
  overflow-y: auto;
}
</style>
<style>
.formItem .el-form-item__label {
  float: none;
}
</style>